<?php
require_once("inc.public.php");
require_once(M_ROOT."/functions/downline/downline_function.php");
require_once(M_ROOT."/functions/comm/comm_function.php");

mysql_query("update $db->settings set value='n' where param='task_run'");
$settings = mysql_fetch_assoc(mysql_query("select * from $db->settings where param='task_run'"));
if($settings['value'] == 'y'){
	exit;
}else{
	mysql_query("update $db->settings set value='y' where param='task_run'");
}

//set_time_limit(0);
$timestart = microtime();
$timestart = explode(" ", $timestart);
echo '<pre>';

$result = credit_cf();
print_r($result);

echo "Peak Memory: ".memory_get_peak_usage()."\n";
$timeend = microtime();echo $timeend;
$timeend = explode(" ", $timeend);
echo "\nTotal Time: ".(($timeend[0] + $timeend[1]) - ($timestart[0] + $timestart[1]));

function credit_cf(){
	//globalize access to pairing_matching_percent, pairing_percent_per_pair, rank_index_a_bv, max_pair_per_day, matching_bonus
	
	global $vars;
	$db=$vars["db"];
	$pairing_percent_per_pair = $vars['pairing_percent_per_pair'];
	$rank_index_a_bv = $vars['rank_index_a_bv'];
	$max_pair_per_day = $vars['max_pair_per_day'];
	$matching_bonus = $vars['matching_bonus'];
	$maintenance_percent = $vars['maintenance_percent'];
	$max_maintain = $vars['max_maintain'];
	
	$in_year=2010;
	$in_month=3;
	$in_day=6;
	
	$start_time=mktime(0, 0, 0, $in_month, $in_day, $in_year);
	$calc_date['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $in_month, $in_day, $in_year));
	$calc_date['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $in_month, $in_day, $in_year));
	$calc_date2['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $in_month, 1, $in_year));
	$calc_date2['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $in_month+1, 0, $in_year));
	$last_day=date('Y-m-d', mktime(0, 0, 0, $in_month, $in_day-1, $in_year));
	$maintain_time=mktime(0, 0, 0, $in_month, 1, $in_year);
	$maintain_year = date("Y", $maintain_time);
	$maintain_month = date("n", $maintain_time);
	
	//matching_max_level = get the maximum of matching level
	//min_maintain = get the minimum maintenance
	$matching_max_level = count($matching_bonus);
	$min_maintain = $vars['min_maintain'];
	
	//setting up - transfer sales record & carryforward into calc table, for faster performance
	$sales_his_safe = false;
	if(!mysql_query("truncate $db->purchase_calc")){
		$sales_his_safe = true;
	}else{
		$ins_total = 0;
		$t = @mysql_num_rows($r=mysql_query("select id, uid, total_bv from $db->purchase where status='confirmed' and member_sale='y' and first_sale='y' and no_bv!='y' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"));
		for($i=0;$i<$t;$i++){
			$his = mysql_fetch_assoc($r);
			$ins .= "('$his[id]', '$his[uid]', '$his[total_bv]'),";
			$ins_total++;
			if($ins_total > 200){
				$ins = rtrim($ins, ',');
				$ins_sql = "insert into $db->purchase_calc (id, uid, total_bv) values $ins";
				if(!mysql_query($ins_sql)){
					$i = $t;
					$sales_his_safe = true;//abort, use slower way
				}
				$ins = '';
				$ins_total = 0;
			}
		}
		if($ins){
			$ins = rtrim($ins, ',');
			$ins_sql = "insert into $db->purchase_calc (id, uid, total_bv) values $ins";
			if(!mysql_query($ins_sql)){
				$sales_his_safe = true;//abort, use slower way
			}
		}
		unset($his, $ins, $ins_sql, $ins_total);
	}
	$carryforward_safe = false;
	if(!mysql_query("truncate $db->member_cf_calc")){
		$carryforward_safe = true;
	}else{
		$ins_total = 0;
		$t = @mysql_num_rows($r=mysql_query("select uid, amount from $db->member_cf where cdate='$last_day'"));
		for($i=0;$i<$t;$i++){
			$his = mysql_fetch_assoc($r);
			$ins .= "('$his[uid]', '$his[amount]'),";
			$ins_total++;
			if($ins_total > 200){
				$ins = rtrim($ins, ',');
				$ins_sql = "insert into $db->member_cf_calc (uid, amount) values $ins";
				if(!mysql_query($ins_sql)){
					$i = $t;
					$carryforward_safe = true;//abort, use slower way
				}
				$ins = '';
				$ins_total = 0;
			}
		}
		if($ins){
			$ins = rtrim($ins, ',');
			$ins_sql = "insert into $db->member_cf_calc (uid, amount) values $ins";
			if(!mysql_query($ins_sql)){
				$carryforward_safe = true;//abort, use slower way
			}
		}
		unset($his, $ins, $ins_sql, $ins_total);
	}
	//end setup
	
	//xxx members = get all the members xxx - we don't we need to filter by maintain 200 as filter is done at reporting - that have personal maintain / purchases of more than min_maintain (200)
	//xxx members = get all the members that have maintain 200BV purchases in the month
	//members = get all the members that is activated
	$t=@mysql_num_rows($r=mysql_query("select id, rank_a from $db->users where activated='y' and id<272 order by id desc"));
	//$t=@mysql_num_rows($r=mysql_query("select id, rank_a from $db->users where id=5121"));
	
	//foreach members
	for($i=0;$i<$t;$i++){
		$member = mysql_fetch_assoc($r);
		//uid = this member[id]
		$uid = $member['id'];
		//if member[rank_index] > 0
		if ($member['rank_a'] > 0){
			//member_legs = get_member_matrix_leg(this member ID, calc_date[start], calc_date[end]) //get this member all legs
			//$zzz = get_member_matrix_leg($uid, $calc_date['start'], $calc_date['end']);
			/*
				member_legs will then looks like this:
				member_legs[index][id]
				member_legs[index][position]
				member_legs[index][volume] - volume should include this day volume (1st sale of a member only) plus any carry forward from previous day if applicable
				member_legs[index][left_volume] - same with volume
				member_legs[index][avolume] - avolume should include only this day volume (1st sale of a member only), without any carry forward
				
				position is the matrix position, avolume is total purchases for this day, sort by largest volume (include carry forward) leg 1st
			*/
			
			//downlines = get 1st level placement downline of uid
			$t2 = @mysql_num_rows($r2=mysql_query("select id, matrix_position from $db->users where matrix_upline='$uid'"));
			for($j=0;$j<$t2;$j++){
				$downline = mysql_fetch_assoc($r2);
				$did = $downline['id'];
				if(!@mysql_num_rows(mysql_query("select * from $db->member_cf where uid='$did' and cdate='2010-03-06'"))){
					$position = $downline['matrix_position'];
					$all_did = $did;
					$uplines[0] = $did;
					$this_volume = 0;
					do{
						//ddownlines = get 1st level placement downlines of uplines
						$t3 = @mysql_num_rows($r3=mysql_query("select id from $db->users where matrix_upline in (".implode(',', $uplines).")"));
						unset ($uplines);
						for($k=0;$k<$t3;$k++){
							$ddownlines = mysql_fetch_assoc($r3);
							$ddid = $ddownlines['id'];
							//if ddid already calculated the volume
							if(false && $member_legss[$ddid]){
								foreach($member_legss[$ddid] as $details){
									$this_volume += $details['avolume'];
								}
							}else{
								$uplines[] = $ddid;
							}
							$all_did .= ','.$ddid;
						}
					}while ($uplines);
					
					//volume = get total sales for period calc_date for all_did + this_volume
					if($sales_his_safe){
						$sql = "select sum(total_bv) from $db->purchase where first_sale='y' and no_bv!='y' and uid in ($all_did) and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'";
					}else{
						$sql = "select sum(total_bv) from $db->purchase_calc where uid in ($all_did)";
					}
					$volume = @mysql_result(mysql_query($sql), 0) or 0;
					//carryfoward = get total carry forward for the downline did for previous day
					if($carryforward_safe){
						$sql = "select amount from $db->member_cf where uid='$did' and cdate='$last_day'";
					}else{
						$sql = "select amount from $db->member_cf_calc where uid='$did'";
					}
					$carryforward = @mysql_result(mysql_query($sql), 0) or 0;
				
					$total_bv = $volume + $this_volume + $carryforward;
					$total_abv = $volume + $this_volume;
					$downlines_id[$j] = $did;
					$downlines_bv[$j] = $total_bv;
					$downlines_dd[$did]['position'] = $position;
					$downlines_dd[$did]['volume'] = $total_bv;
					$downlines_dd[$did]['avolume'] = $total_abv;
				}
			}
			if($downlines_id && $downlines_bv){
				for($j=0,$t2=count($downlines_id);$j<$t2;$j++){
					$legs[$j]["id"]=$downlines_id[$j];
					$legs[$j]['position'] = $downlines_dd[$downlines_id[$j]]['position'];
					$legs[$j]['volume']=$downlines_bv[$j];
					$legs[$j]['left_volume'] = $downlines_bv[$j];
					$legs[$j]['avolume'] = $downlines_dd[$downlines_id[$j]]['avolume'];
				}
			}
			$member_legs = $legs;
			$member_legss[$uid] = $legs;
			unset ($legs, $downlines_id, $downlines_bv, $uplines, $all_did);
			
			//carry forward for all legs with left_volume > 0
			$paid_comm = mysql_num_rows(mysql_query("select * from $db->member_comm where uid='$uid' and type='p' and year='$in_year' and month='$in_month' and day='$in_day' and status='confirmed'"));
			for($j=0,$t2=count($member_legs);$j<$t2;$j++){
				if ($member_legs[$j]['left_volume'] > 0){
					//insert into member_cf with uid = member_legs[index][id], leg = member_legs[index][position], amount = member_legs[index][left_volume], year = year, month = month, day = day
					$cdate = date('Y-m-d', mktime(0,0,0,3,9,2010));
					if(mysql_num_rows(mysql_query("select * from $db->member_cf where uid='{$member_legs[$j]['id']}' and cdate='$cdate'"))){
						$sql = "update $db->member_cf set amount=amount+{$member_legs[$j]['left_volume']} where uid='{$member_legs[$j]['id']}' and cdate='$cdate' limit 1";
					}else{
						$sql="insert into $db->member_cf (uid, leg, amount, cdate) values ('{$member_legs[$j]['id']}', '{$member_legs[$j]['position']}', '{$member_legs[$j]['left_volume']}', '$cdate')";
					}
					$insert_comm_detail="UID: $uid Carryforward Amount: {$member_legs[$j]['left_volume']} Leg: {$member_legs[$j]['position']} (DID: {$member_legs[$j]['id']})<br />\n";
					//if insert fail
						//record error in the variable insert_cf_error
					echo "uid:$uid $sql".($paid_comm? " <span style='color:red;'>Paid comm</span>" : '')."\n";
					if(!mysql_query($sql)){
						$insert_cf_error.=$insert_comm_detail."SQL: $sql<br />\n";
					}
				}
			}
		}
	}
	
	if($insert_cf_error || $insert_pair_error || $insert_matching_error || $insert_main_err){
		$status = false;
	}else{
		$status = true;
	}
	
	$errmsg = ($insert_cf_error? "\nFailed Recording Carry Forward:\n\n$insert_cf_error" : "").
	($insert_pair_error? "Failed Pairing Commission Calculation:<br />\n<br />\n$insert_pair_error" : "").
	($insert_matching_error? "Failed Matching Commission Calculation:<br />\n<br />\n$insert_matching_error" : "").
	($insert_main_error? "Failed Maintenance Calculation:<br />\n<br />\n$insert_main_error" : "").
	($update_ew_err? "\nError crediting $vars[ewallet_title]:\n\n$update_ew_err" : "").
	($insert_ewrec_err? "\nError crediting $vars[ewallet_title] transactin record:\n\n$insert_ewrec_err" : "").
	($update_sw_err? "\nError crediting $vars[swallet_title]:\n\n$update_sw_err" : "").
	($insert_swrec_err? "\nError crediting $vars[swallet_title] transactin record:\n\n$insert_swrec_err" : "").
	($update_mw_err? "\nError crediting $vars[mwallet_title]:\n\n$update_mw_err" : "").
	($insert_mwrec_err? "\nError crediting $vars[mwallet_title] transactin record:\n\n$insert_mwrec_err" : "");
	
	return array('status'=>$status, 'errmsg'=>$errmsg);
}
?>